<template>
  <el-config-provider :locale="zhCn" :size="size" :z-index="zIndex">
    <router-view />
    <el-dialog
      :model-value="userStore.temuDialog"
      :title="userStore.temuDialogTitle"
      width="800px"
      lock-scroll
      :show-close="userStore.temuShowClose"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      @close="userStore.temuDialog = false"
    >
      <div class="temu-login-container">
        <el-form
          :model="temuForm"
          :rules="temuRules"
          class="login-form"
          label-position="left"
        >
          <div class="title-container">
            <h3 class="title">登录拼多多</h3>
          </div>
          <el-form-item prop="username">
            <span class="svg-container">
              <svg-icon name="user" />
            </span>
            <el-input
              ref="refUsername"
              v-model="temuForm.username"
              placeholder="手机号"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon name="password" />
            </span>
            <el-input
              ref="refPassword"
              v-model="temuForm.password"
              :type="passwordType"
              placeholder="密码"
              name="password"
              tabindex="2"
              autocomplete="off"
              @keyup.enter="loginTemu"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon
                :name="passwordType === 'password' ? 'eye' : 'eye-open'"
              />
            </span>
          </el-form-item>
          <el-button
            :loading="temuLoading"
            type="primary"
            style="width: 100%; margin-bottom: 20px; margin-top: 30px"
            @click.prevent="loginTemu"
          >
            登 录
          </el-button>
        </el-form>
      </div>
    </el-dialog>
  </el-config-provider>
</template>

<script setup>
import { ElConfigProvider, ElMessageBox } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { computed, onMounted, reactive, ref, toRefs, watch } from 'vue'
import { useUserStore } from '@/store/user'
import { useSettingsStore } from '@/store/settings'
import {
  checkCookieStatus,
  heartBeats,
  loginTemuSys,
  saveServCookie,
  stopRob
} from '@/api/user'
import {
  getUserInfo,
  sysNoticeDialog,
  sysNoticeDialogByIdc,
  sysNoticeDialogNotTip
} from '@/api/auth'
import { useRouter } from 'vue-router'
import { getToken } from '@/utils/storage'

const settingsStore = useSettingsStore()
const userStore = useUserStore()

const validateUsername = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入账号'))
  } else {
    callback()
  }
}
const validatePassword = (rule, value, callback) => {
  if (value.length < 6) {
    callback(new Error('请输入有效密码'))
  } else {
    callback()
  }
}

let validTimer = null
const state = reactive({
  zIndex: 3000
})
const { zIndex } = toRefs(state)
const heartTimer = ref(null)
const size = computed(() => settingsStore.size)
const userToken = computed(() => userStore.token)
// 登录失效后，不需要再检查
const needCheckCookie = ref(true)
const router = useRouter()
const needGetPddUserInfo = ref(true)
const passwordType = ref('password')

const temuForm = ref({
  username: '',
  password: ''
})
const temuRules = ref({
  username: [{ required: true, trigger: 'blur', validator: validateUsername }],
  password: [{ required: true, trigger: 'blur', validator: validatePassword }]
})
const temuLoading = ref(false)

const showPwd = () => {
  if (passwordType.value === 'password') {
    passwordType.value = 'text'
  } else {
    passwordType.value = 'password'
  }
}
const checkCookie = async () => {
  const { is_avaliable } = await checkCookieStatus()
  if (!is_avaliable) {
    needCheckCookie.value = false
    userStore.showTemuDialog('拼多多登录失效', false)
    // ElMessageBox({
    //   message: `拼多多登录失效，请在当前浏览器重新登录拼多多后点击确定 \n （确定之后，浏览器会自动重启）`,
    //   title: '登录失效',
    //   confirmButtonText: '确定',
    //   lockScroll: true,
    //   showClose: false,
    //   showCancelButton: false,
    //   distinguishCancelAndClose: true,
    //   beforeClose: (action, instance, done) => {
    //     if (action === 'confirm') {
    //       done()
    //     }
    //   },
    //   type: 'warning'
    // })
    //   .then(async () => {
    //     await userStore.pddAuth(true)
    //     needCheckCookie.value = true
    //     needGetPddUserInfo.value = true
    //   })
    //   .catch(() => {
    //     window.location.reload()
    //   })
  } else {
    if (needGetPddUserInfo.value) {
      needGetPddUserInfo.value = false
      await userStore.pddAuth()
      await userStore.getPddInfo()
    }
  }
}
const loginTemu = async () => {
  temuLoading.value = true
  try {
    await loginTemuSys(temuForm.value)
    await userStore.pddAuth(true)
    needCheckCookie.value = true
    needGetPddUserInfo.value = true
    temuLoading.value = false
    userStore.hideTemuDialog()
  } catch (e) {
    window.location.reload()
  }
}

watch(
  () => userToken.value,
  (val) => {
    clearInterval(validTimer)
    if (val) {
      validTimer = setInterval(() => {
        getUserInfo()
          .then((res) => {
            if (!res || res?.user_info?.user_level === 0) {
              stopRob()
            }
          })
          .catch(() => {
            clearInterval(validTimer)
            ElMessageBox({
              message: `登录已失效，请重新登录！`,
              title: '登录失效',
              confirmButtonText: '确定',
              lockScroll: true,
              showClose: false,
              showCancelButton: false,
              distinguishCancelAndClose: true,
              beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                  done()
                }
              },
              type: 'warning'
            }).then(async () => {
              await userStore.logout()
              router.push(`/login`)
            })
          })
      }, 10000)
      userStore.validTokenTimer = validTimer
    }
  },
  { immediate: true }
)

const startHeartBeats = async () => {
  heartBeats().catch(() => {})
  heartTimer.value = setInterval(() => {
    heartBeats().catch((e) => {
      console.log('heart err>>>', e)
    })
  }, 30000)
}
const sleep = (time) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve()
    }, time)
  })
}
const loopExec = async () => {
  if (userToken.value && needCheckCookie.value) {
    try {
      await checkCookie()
    } catch (e) {
      //
    }
  }
  await sleep(10000)
  await loopExec()
}

onMounted(() => {
  startHeartBeats()
  loopExec()
  if (getToken()) {
    saveServCookie(getToken())
  }
})
</script>

<style lang="scss" scoped>
$dark_gray: #889aa4;
$bg: #283443;
$light_gray: #fff;
$cursor: #333;

.temu-login-container {
  min-height: 100%;
  width: 100%;
  overflow: hidden;

  :deep(.el-input) {
    flex: 1;
    display: inline-block;
    height: 47px;

    .el-input__wrapper {
      width: 100%;
      padding: 0;
      background-color: transparent;
      box-shadow: none;

      input {
        background: transparent;
        border: 0px;
        appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: #333;
        height: 47px;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
    margin: 0 auto;
    overflow: hidden;
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: #333;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
